package com.yss.common.core.utils.easyexecl;


import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yss.common.core.utils.DateUtils;
import com.yss.common.core.utils.StringUtils;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description: yyyy-MM-dd easyExcel 日期转换
 */
public class DateConverter implements Converter<Date> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return Converter.super.supportJavaTypeKey();
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return Converter.super.supportExcelTypeKey();
    }

    @Override
    public WriteCellData<?> convertToExcelData(Date value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (null != value) {
            Field field = contentProperty.getField();
            JsonFormat jsonFormat = field.getAnnotation(JsonFormat.class);
            if (DateUtils.YYYY_MM_DD_HH_MM_SS.equals(jsonFormat.pattern())) {
                SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.YYYY_MM_DD_HH_MM_SS);
                String dateValue = sdf.format(value);
                return new WriteCellData<>(dateValue);
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.YYYY_MM_DD);
                String dateValue = sdf.format(value);
                return new WriteCellData<>(dateValue);
            }
        }
        return new WriteCellData<>("");
    }

    //将excel的数据类型转为java数据类型
    @Override
    public Date convertToJavaData(ReadCellData readCellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String stringValue = readCellData.getStringValue();
        if (StringUtils.isEmpty(stringValue)) {
            return null;
        }
        Field field = excelContentProperty.getField();
        JsonFormat jsonFormat = field.getAnnotation(JsonFormat.class);
        if (DateUtils.YYYY_MM_DD_HH_MM_SS.equals(jsonFormat.pattern())) {
            return DateUtils.strToDateByFormat(stringValue, DateUtils.YYYY_MM_DD_HH_MM_SS);
        } else {
            return DateUtils.strToDateByFormat(stringValue, DateUtils.YYYY_MM_DD);
        }
    }
}
